//
//  FKFastShareChildVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/20.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKFastShareChildVC.h"
#import "FKFastShareCell.h"
#import "FKFastShareModel.h"
#import "FKAreaAndTradeView.h"
#import "FKTrade.h"
#import <GKPhotoBrowser.h>
//#import <Photos/PHAsset.h>
//#import <Photos/PHAssetChangeRequest.h>
#import "FKShareChooseImageView.h"
#import "FKShareNowView.h"
#import <UShareUI/UShareUI.h>
#import "FKSharePhotoBrower.h"
#import "FKFastShareTool.h"
#import <Photos/PHAssetChangeRequest.h>

@interface FKFastShareChildVC ()<FKFastShareCellDelegate>

@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) NSMutableDictionary *param;
@property(nonatomic, assign) NSInteger page;

/** 保存分享素材的id，添加次数需要 */
@property (nonatomic, copy) NSString *itemId;

@end

@implementation FKFastShareChildVC


- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}

- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
        _param[@"pagesize"] = @(10);
    }
    return _param;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.param[@"type"] = @(self.type);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
    self.tableView.tableFooterView = [UIView new];
    self.tableView.autoresizingMask = UIViewAutoresizingNone;
    
    if (self.type == 1) {
        [self loadArea];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKFastShareCell *cell = [FKFastShareCell cellWith:tableView];
    cell.delegate = self;
    cell.data = self.datas[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKFastShareModel *model = self.datas[indexPath.row];
    return model.cellH;
}



#pragma mark - FKFastShareCellDelegate
- (void)fastShareCell:(FKFastShareCell *)cell didTapImageView:(NSInteger)index
{
    if (self.type == 1) {
        FKFastShareModel *model = cell.data;
        FKSharePhotoBrower *brower = [[FKSharePhotoBrower alloc] init];
        brower.saleTime = model.time_arr[@"share_desc"][@"sale_desc"];
        brower.activeTime = model.time_arr[@"share_desc"][@"active_desc"];
        brower.images = model.imgs;
        brower.url = model.item_url;
        brower.currentIndex = index;
        [brower show];
    } else {
        FKFastShareModel *model = cell.data;
        NSMutableArray *photos = [NSMutableArray new];
        for (NSString *url in model.imgs) {
            GKPhoto *photo = [GKPhoto new];
            photo.url = [NSURL URLWithString:url];
            [photos addObject:photo];
        }
        GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:index];
        browser.showStyle = GKPhotoBrowserShowStyleNone;
        [browser showFromVC:self];
    }
}

- (void)fastShareCellDidClickedCopyBtn:(FKFastShareCell *)cell
{
    FKFastShareModel *model = cell.data;
    self.itemId = model.id;
    [self addShareCount];
    
    // 将文字添加到剪贴板
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = model.info;
    NSDictionary *userInfo = [FKCacheTool userInfo];
    if (model.imgs.count > 0) {
        if (self.type == 1) {
            [SVProgressHUD show];
            [FKFastShareTool createPhotosWith:model.imgs qrcodeUrl:model.item_url saleTime:model.time_arr[@"share_desc"][@"sale_desc"] activeTime:model.time_arr[@"share_desc"][@"active_desc"] level:userInfo[@"level"] complete:^(NSArray<UIImage *> * _Nonnull images) {
                [FKFastShareTool saveImages:images completion:^{
                    [SVProgressHUD showSuccessWithStatus:@"文案复制成功"];
                }];
            }];
        } else {
            [SVProgressHUD show];
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_group_t group = dispatch_group_create();
            for (int i = 0 ; i < model.imgs.count; i++) {
                NSString *url = model.imgs[i];
                UIImageView *imageView = [UIImageView new];
                [imageView sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    dispatch_group_enter(group);
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                    } completionHandler:^(BOOL success, NSError * _Nullable error) {
                        dispatch_group_leave(group);
                    }];
                }];
            }
            dispatch_group_notify(group, queue, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    FKLog(@"全部保存完毕");
                    [SVProgressHUD showSuccessWithStatus:@"文案复制成功"];
                });
                
            });
        }
    } else {
        [SVProgressHUD showSuccessWithStatus:@"文案复制成功"];
    }
}

///** 保存图片到相册 */
//- (void)saveImages:(NSArray<UIImage *> *)images completion:(void (^)(void))completion
//{
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_group_t group = dispatch_group_create();
//    for (UIImage *image in images) {
//        dispatch_group_enter(group);
//        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
//        } completionHandler:^(BOOL success, NSError * _Nullable error) {
//            dispatch_group_leave(group);
//        }];
//    }
//
//    dispatch_group_notify(group, queue, ^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (completion) completion();
//        });
//        FKLog(@"全部保存完毕");
//    });
//}

- (void)fastShareCellDidClickedWechatTimeline:(FKFastShareCell *)cell
{
    FKFastShareModel *model = cell.data;
    self.itemId = model.id;
    NSDictionary *userInfo = [FKCacheTool userInfo];

    if ([model.market_type isEqualToString:@"1"]) { // 图片类型
        // 生成带二维码的图片
        [SVProgressHUD show];
        [FKFastShareTool createPhotosWith:model.imgs qrcodeUrl:model.item_url saleTime:model.time_arr[@"share_desc"][@"sale_desc"] activeTime:model.time_arr[@"share_desc"][@"active_desc"] level:userInfo[@"level"] complete:^(NSArray<UIImage *> * _Nonnull images) {
            [SVProgressHUD dismiss];
            FKShareChooseImageView *view = [[FKShareChooseImageView alloc] init];
            view.type = 1;
            view.images = images;
            [view show];
            view.bottomBtnBlock = ^(NSArray * _Nonnull urls) {
                // 保存图片到相册
                [SVProgressHUD show];
                [FKFastShareTool saveImages:images completion:^{
                    [SVProgressHUD dismiss];
                    FKShareNowView *view = [[FKShareNowView alloc] init];
                    [view show];
                }];
            };
        }];
    } else { // 分享链接
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:model.url_title descr:model.info thumImage:[UIImage imageNamed:@"AppIcon"]];
        shareObject.webpageUrl = model.url;
        messageObject.shareObject = shareObject;
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"分享失败"];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                [self addShareCount];
            }
        }];
    }
}

- (void)fastShareCellDidClickedWechatSession:(FKFastShareCell *)cell
{
    __block FKFastShareModel *model = cell.data;
    self.itemId = model.id;
    NSDictionary *userInfo = [FKCacheTool userInfo];

    if ([model.market_type isEqualToString:@"1"]) {
        fkWeakSelf(self);
        [SVProgressHUD show];
        [FKFastShareTool createPhotosWith:model.imgs qrcodeUrl:model.item_url saleTime:model.time_arr[@"share_desc"][@"sale_desc"] activeTime:model.time_arr[@"share_desc"][@"active_desc"] level:userInfo[@"level"] complete:^(NSArray<UIImage *> * _Nonnull images) {
            [SVProgressHUD dismiss];
            FKShareChooseImageView *view = [[FKShareChooseImageView alloc] init];
            view.type = 2;
            view.images = images;
            [view show];
            view.bottomBtnBlock = ^(NSArray * _Nonnull urls) {
                __block NSMutableArray *activityItems = [NSMutableArray array];
                [activityItems addObject:model.info];
                for (UIImage *image in images) {
                    [activityItems addObject:image];
                }
                UIActivityViewController *activityVc = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
                
                activityVc.excludedActivityTypes = @[UIActivityTypePostToFacebook     ,
                                                     UIActivityTypePostToTwitter      ,
                                                     UIActivityTypePostToWeibo        ,
                                                     UIActivityTypeMessage            ,
                                                     UIActivityTypeMail               ,
                                                     UIActivityTypePrint              ,
                                                     UIActivityTypeCopyToPasteboard   ,
                                                     UIActivityTypeAssignToContact    ,
                                                     //                  UIActivityTypeSaveToCameraRoll   ,
                                                     UIActivityTypeAddToReadingList   ,
                                                     UIActivityTypePostToFlickr       ,
                                                     UIActivityTypePostToVimeo        ,
                                                     UIActivityTypePostToTencentWeibo ,
                                                     //                  UIActivityTypeAirDrop            ,
                                                     UIActivityTypeOpenInIBooks       ,
                                                     //                                                     UIActivityTypeMarkupAsPDF
                                                     ];
                [weakself presentViewController:activityVc animated:YES completion:nil];
                activityVc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
                    if (completed) {
                        FKLog(@"分享成功");
                        [self addShareCount];
                    } else {
                        FKLog(@"分享失败");
                    }
                };
            };
        }];
        
    } else {
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:model.url_title descr:model.info thumImage:[UIImage imageNamed:@"AppIcon"]];
        shareObject.webpageUrl = model.url;
        messageObject.shareObject = shareObject;
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"分享失败"];
            } else {
                [SVProgressHUD showSuccessWithStatus:@"分享成功"];
                [self addShareCount];
            }
        }];
    }
}

#pragma mark - 网络请求
- (void)loadArea
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"area_id"] = @"20";
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=areaList" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            
            CGFloat headerH = 0;
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
            NSArray *areas = result.data[@"list"];
            CGFloat itemH = fk_adjustW(20);
            if (areas.count > 0) {
                CGFloat itemW = (fkScreenW - fk_adjustW(58) - 5 * 3 - 12) / 4.f;
                NSMutableArray *items = [NSMutableArray array];
                for (NSDictionary *area in areas) {
                    NSMutableDictionary *areaItem = [NSMutableDictionary dictionary];
                    [items addObject:areaItem];
                    areaItem[@"cellName"] = @"FKAreaItemCell";
                    areaItem[@"data"] = area;
                    areaItem[@"itemSize"] = @(CGSizeMake(itemW, itemH));
                }
                data[@"areas"] = items;
                
                NSInteger rows = areas.count % 4 == 0 ? areas.count / 4 : areas.count / 4 + 1;
                headerH = fk_adjustW(12) + rows * itemH + (rows - 1) * 5 + fk_adjustW(15);
            }
            data[@"areaH"] = @(headerH);
            
            NSArray *trades = [FKTrade mj_objectArrayWithKeyValuesArray:result.data[@"trade"]];
            
            if (trades.count > 0) {
                CGFloat titleW = [@"热门商圈:" sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(10);
                CGFloat beginX = 12 + titleW + 5;
                CGFloat itemX = 0;
                CGFloat itemRight = 0;
                CGFloat itemY = 0;
                for (FKTrade *trade in trades) {
                    CGFloat itemW = [trade.name sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(14);
                    
                    if ([trade isEqual:trades.firstObject]) {
                        itemX = beginX;
                        headerH += itemH;
                    }
                    itemRight = (itemX + itemW);
                    if (itemRight > fkScreenW - 12) {
                        itemX = 12;
                        itemRight = itemX;
                        itemY += (itemH + 5);
                        headerH += (itemH + 5);
                    }
                    trade.itemFrame = CGRectMake(itemX, itemY, itemW, itemH);
                    itemX += (itemW + 5);
                }
                data[@"trades"] = trades;
                headerH += fk_adjustW(10);
            }
            data[@"headerH"] = @(headerH);
            
            FKAreaAndTradeView *header = [[FKAreaAndTradeView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, headerH)];
            self.tableView.tableHeaderView = header;
            header.fastShare = true;
            header.data = data;
            fkWeakSelf(self);
            header.didSelectedArea = ^(NSDictionary * _Nonnull param) {
                [weakself.param addEntriesFromDictionary:param];
                [weakself.tableView.mj_header beginRefreshing];
                // 刷新商圈数据
                [weakself loadTrades:param[@"region_id"]];
            };
            header.didSelectedTrade = ^(NSDictionary * _Nonnull param) {
                [weakself.param addEntriesFromDictionary:param];
                [weakself.tableView.mj_header beginRefreshing];
            };
        }
    } failure:nil];
}

/** 刷新头部商圈数据 */
- (void)loadTrades:(NSString *)region_id
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"area_id"] = [FKCacheTool storeId];
    param[@"region_id"] = region_id;
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=areaList" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            if (self.tableView.tableHeaderView) {
                FKAreaAndTradeView *header = (FKAreaAndTradeView *)self.tableView.tableHeaderView;
                
                NSArray *trades = [FKTrade mj_objectArrayWithKeyValuesArray:result.data[@"trade"]];
                CGFloat tradeH = 0;
                if (trades.count > 0) {
                    CGFloat titleW = [@"热门商圈:" sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(10);
                    CGFloat beginX = 12 + titleW + 5;
                    CGFloat itemX = 0;
                    CGFloat itemY = 0;
                    CGFloat itemRight = 0;
                    CGFloat itemH = fk_adjustW(20);
                    for (FKTrade *trade in trades) {
                        CGFloat itemW = [trade.name sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(14);
                        
                        NSInteger index = [trades indexOfObject:trade];
                        if (index == 0) {
                            itemX = beginX;
                        }
                        
                        itemRight = (itemX + itemW);
                        if (itemRight > fkScreenW - 12) {
                            itemX = 12;
                            itemRight = itemX;
                            itemY += (itemH + 5);
                            tradeH += (itemH + 5);
                        }
                        trade.itemFrame = CGRectMake(itemX, itemY, itemW, itemH);
                        itemX += (itemW + 5);
                        
                        if ([trade isEqual:trades.firstObject]) {
                            tradeH += itemH;
                        }
                    }
                    tradeH += fk_adjustW(10);
                }
                
                [header updateTrades:trades tradeH:tradeH];
                self.tableView.tableHeaderView = header;
            }
        }
    } failure:nil];
}

- (void)loadData
{
    self.page = 1;
    self.param[@"page"] = @(self.page);
    [FKHttpTool postWithSuffix:@"m=Home&c=Market&a=index" param:self.param success:^(FKBaseResult *result) {
        [self.tableView.mj_header endRefreshing];
        if (result.isSuccess) {
            NSDictionary *info = result.data[@"info"];
            self.datas = [FKFastShareModel mj_objectArrayWithKeyValuesArray:info[@"list"]];
            [self.tableView reloadData];
            if (self.datas.count > 0) self.page++;
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData
{
    self.param[@"page"] = @(self.page);
    [FKHttpTool postWithSuffix:@"m=Home&c=Market&a=index" param:self.param success:^(FKBaseResult *result) {
        [self.tableView.mj_footer endRefreshing];
        if (result.isSuccess) {
            NSDictionary *info = result.data[@"info"];
            NSArray *newArray = [FKFastShareModel mj_objectArrayWithKeyValuesArray:info[@"list"]];
            if (newArray.count > 0) {
                NSMutableArray *array = [NSMutableArray arrayWithArray:self.datas];
                [array addObjectsFromArray:newArray];
                self.datas = array;
                [self.tableView reloadData];
                self.page++;
            } else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

/**
 添加分享次数
 itemsId：素材id
 */
- (void)addShareCount
{
    if (!self.itemId) return;
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"market_id"] = self.itemId;
    self.itemId = nil; // 用完记得清空
    [FKHttpTool postWithSuffix:@"m=Home&c=Market&a=setIncShareNum" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            FKLog(@"-----添加分享次数成功-----");
        }
    } failure:nil];
}

@end
